"""
# @Time : 2023/8/13 17:10
# @Author : goose
"""
import pymysql


class ConnectDB:
    conn = None
    cursor = None

    # 1.创建连接
    @classmethod
    def get_conn(cls):
        if cls.conn is None:
            cls.conn = pymysql.connect(host="192.168.0.107",
                                       port=3306,
                                       user="root",
                                       password="root",
                                       database="tpshop2.0"
                                       )
        return cls.conn

    # 2.获取游标
    @classmethod
    def get_cursor(cls):
        if cls.cursor is None:
            cls.cursor = cls.get_conn().cursor()
        return cls.cursor

    # 3.1执行sql(select)
    @classmethod
    def exec_sql(cls, sql):
        try:
            cursor = cls.get_cursor()
            cursor.execute(sql)
            if sql.split()[0].lower() == "select":
                return cursor.fetchall()
            else:
                cls.conn.commit()
                return cursor.rowcount
        except Exception as e:
            print(e)
            cls.conn.rollback()
        finally:
            cls.close_cursor()
            cls.close_conn()

    # 4.关闭游标
    @classmethod
    def close_cursor(cls):
        cls.cursor = ConnectDB.get_cursor()
        cls.cursor.close()
        cls.cursor = None

    # 5.关闭连接
    @classmethod
    def close_conn(cls):
        cls.conn = ConnectDB.get_conn()
        cls.conn.close()
        cls.conn = None


conn = ConnectDB.exec_sql("select user_id ,mobile from `tpshop2.0`.tp_users;")
print(conn)
ConnectDB.close_cursor()
ConnectDB.close_conn()
